var express = require('express');
var router = express.Router();
var debug = require('debug')('upload');
var multer = require('multer');
var path = require('path');

router.get('/', function (req, res, next) {
    res.redirect('/html/upload.html');
});

var midMulter = multer({
    dest: './uploads/',

    changeDest: function (dest, req, res) {
        debug('previous dest=' + dest + ', current dest=' + dest);
        var nowDest = path.join(__dirname, '../../../uploads');
        return nowDest;
    },

    onFileUploadStart: function (file, req, res) {
        debug('onFileUploadStart');
    },

    onFileUploadComplete: function (file, req, res) {
        // debug('onFileUploadComplete, name=' + file.path);
        var fileId = file.path.split('/').pop();
        req.body.fileId = fileId;
        debug('onFileUploadComplete, fileId=' + fileId);
        // upload to 7niu
        upload(file.path, fileId).then(function (reply) {
            res.status(200).end(JSON.stringify({
                errCode: 0,
                errMsg: 'ok',
                url: reply
            }));
        }, function (err) {
            res.status(200).end(JSON.stringify({
                errCode: 500,
                errMsg: err
            }));
        })
    },

    onParseEnd: function (req, next) {
        debug('onParseEnd');
        req.body = require('qs').parse(req.body);
        debug(req.body);
        next();
    }
});

router.post('/', function (req, res, next) {
    debug('multer start');
    // midMulter(req, res, next);
    midMulter(req, res, function () {
        debug('multer done');
        //res.status(200).end(JSON.stringify({
        //    errCode: 0,
        //    errMsg: 'ok'
        //}));
    });
});

var qiniuApi = require('../../../qiniu/qiniuApi.js');

function upload(path, fileId) {
    return qiniuApi.addNew(fileId, path).then(function (reply) {
        debug('upload to qiniu succ');
        debug(reply);
        return Promise.resolve(reply);
    }, function (err) {
        debug('upload to qiniu err');
        debug(err);
        return Promise.reject(err);
    });
}


module.exports = exports = router;